﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;
using Process.Infastructure;

namespace Process.Api.Application.Handler
{
    public class DeleteProcessFlowHandler : IRequestHandler<DeleteProcessFlowCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<ProcessFlow> _processFlowRepo;
        private readonly IProcessRepository<FlowProcessRelation> _flowprocessRelation;
        private readonly ProcessDbContext _db;

        public DeleteProcessFlowHandler(IProcessRepository<ProcessFlow> processFlowRepo, IProcessRepository<FlowProcessRelation> flowprocessRelation, ProcessDbContext db)
        {
            _processFlowRepo = processFlowRepo;
            _flowprocessRelation = flowprocessRelation;
            _db = db;
        }
        /// <summary>
        /// 删除工艺流程
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(DeleteProcessFlowCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // 查询目标流程
            var flow = _processFlowRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && x.IsDelete == false);
            if (flow == null)
            {
                result.Code = ErrorStatus.Error;
                result.Message = "未找到对应的工艺流程或已删除";
                result.Data = 0;
                return result;
            }

            // 同库事务：保证关系与流程删除一致
            using (var tx = await _db.Database.BeginTransactionAsync(cancellationToken))
            {
                try
                {
                    // 查询并删除所有关联关系记录（先删关系，避免外键约束）
                    var relations = _flowprocessRelation.GetAllAsync().Where(x => x.ProcessFlowId == request.Id).ToList();
                    if (relations.Any())
                    {
                        await _flowprocessRelation.DeleteRangeAsync(relations);
                    }

                    // 删除流程本身
                    var affected = await _processFlowRepo.DeleteAsync(flow);

                    await tx.CommitAsync(cancellationToken);

                    result.Code = affected > 0 ? ErrorStatus.Success : ErrorStatus.Error;
                    result.Message = affected > 0 ? "删除工艺流程成功" : "删除工艺流程失败";
                    result.Data = affected;
                    return result;
                }
                catch
                {
                    await tx.RollbackAsync(cancellationToken);
                    result.Code = ErrorStatus.Error;
                    result.Message = "删除工艺流程失败，事务已回滚";
                    result.Data = 0;
                    return result;
                }
            }
        }
    }
}
